<script lang="ts" setup>
import type { LowcodeDatasourceApi } from '#/api/lowcode/datasource';

import { computed, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { message } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import { createDatasourceConfig, getDatasourceConfig, updateDatasourceConfig, handleDatasourceSync } from '#/api/lowcode/datasource';
import { $t } from '#/locales';

import { useFormSchema } from '../data';

const emit = defineEmits(['success']);
const formData = ref<LowcodeDatasourceApi.DatasourceConfig>();
const getTitle = computed(() => {
  return formData.value?.id
    ? $t('ui.actionTitle.edit', ['数据源'])
    : $t('ui.actionTitle.create', ['数据源']);
});

const [Form, formApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
  },
  wrapperClass: 'grid-cols-2',
  layout: 'horizontal',
  schema: useFormSchema(),
  showDefaultActions: false,
});

const [Modal, modalApi] = useVbenModal({
  async onConfirm() {
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
    modalApi.lock();
    // 提交表单
    const data = (await formApi.getValues()) as LowcodeDatasourceApi.DatasourceConfig;
    
    // 如果是编辑模式，确保包含ID
    if (formData.value?.id) {
      data.id = formData.value.id;
    }
    
    try {
      // 执行创建或更新操作
      const operation = formData.value?.id ? 'update' : 'create';
      await (formData.value?.id ? updateDatasourceConfig(data) : createDatasourceConfig(data));
      
      // 处理同步 - 检查是否启用自动同步
      const autoSync = localStorage.getItem('datasource-auto-sync') === 'true';
      const syncResult = await handleDatasourceSync(operation, data.id, autoSync);
      
      // 关闭并提示
      await modalApi.close();
      emit('success');
      
      message.success({
        content: syncResult.message,
        duration: syncResult.needSync ? 8 : 3, // 需要同步时显示更长时间
      });
    } catch (error: any) {
      console.error('操作失败:', error);
      
      let errorMessage = '操作失败，请检查输入信息';
      if (error?.response?.data?.message) {
        errorMessage = error.response.data.message;
      } else if (error?.message) {
        errorMessage = error.message;
      }
      
      message.error(errorMessage);
    } finally {
      modalApi.unlock();
    }
  },
  async onOpenChange(isOpen: boolean) {
    if (!isOpen) {
      formData.value = undefined;
      return;
    }
    // 加载数据
    const data = modalApi.getData<LowcodeDatasourceApi.DatasourceConfig>();
    
    if (!data || !data.id) {
      return;
    }
    
    modalApi.lock();
    try {
      const result = await getDatasourceConfig(data.id as number);
      
      // 检查响应结构
      let datasourceData = result;
      if (result && typeof result === 'object' && 'data' in result) {
        datasourceData = result.data;
      }
      
      formData.value = datasourceData;
      // 设置到 values
      await formApi.setValues(formData.value);
    } catch (error: any) {
      let errorMessage = '加载数据源配置失败';
      if (error?.response?.data?.message) {
        errorMessage = error.response.data.message;
      } else if (error?.message) {
        errorMessage = error.message;
      }
      message.error(errorMessage);
    } finally {
      modalApi.unlock();
    }
  },
  title: getTitle,
});

defineExpose({
  modalApi,
});


</script>

<template>
  <Modal>
    <Form />
  </Modal>
</template>